 //
//  ZYAppointmentController.m
//  BestLearning
//
//  Created by Ethan on 2017/9/26.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "ZYAppointmentController.h"
#import "ZYAppointmentCell.h"
#define kCell @"cell"
#define kCelll @"celll"
#import "ZYAlreadyAgreedController.h"
#import "ZYAgreedDetailesController.h"
#import "ZYAppointmentModel.h"
#define DEVICE_IS_iPhone5 ([[UIScreen mainScreen] bounds].size.height >= 568)
#define DEVICE_IS_iPhone4 ([[UIScreen mainScreen] bounds].size.height == 480)
#import "ZYProposalController.h"
#import "IQKeyboardManager.h"
#import "ZYAppointTowCell.h"
#import "ZYAppointmentTowModel.h"
#import "keyBoardToolView.h"

@interface ZYAppointmentController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate,ZYAppointTowDelegate,keyBoardToolViewDelegate>
@property (nonatomic,strong) NSMutableArray *dataSource;
@property (nonatomic,strong) NSMutableArray *dataTowSource;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UIView *allView;
@property (nonatomic,copy)NSString *selectId;
@property (nonatomic, strong) keyBoardToolView *keyBoardView;
@property (nonatomic, assign) CGFloat keyBoardHeight;

@end

@implementation ZYAppointmentController




- (NSMutableArray *)dataTowSource {
    
    if (_dataTowSource == nil) {
        self.dataTowSource = [NSMutableArray array];
    }
    
    return _dataTowSource;
    
    
}

- (NSMutableArray *)dataSource {
    
    if (_dataSource == nil) {
        self.dataSource = [NSMutableArray array];
    }
    
    return _dataSource;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"总结";
    self.view.backgroundColor = ColorRGB(247, 245, 245);
    
    UIBarButtonItem *itemA = [[UIBarButtonItem alloc] initWithTitle:@"我的约定" style:(UIBarButtonItemStylePlain) target:self action:@selector(itemAction)];
    
    self.navigationItem.rightBarButtonItem = itemA;
    
    
    [self setNetWork];
    [self setUpSuperView];

     [self registerKeyBoardNotification];
    [self initWithKeyBoardToolView];
}

- (void)initWithKeyBoardToolView {
    self.keyBoardView = [[keyBoardToolView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 40)];
    self.keyBoardView.backgroundColor = ColorRGB(247, 245, 245);
    self.keyBoardView.delegate = self;
    [self.view addSubview:self.keyBoardView];
}

- (void)registerKeyBoardNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyBoardHide:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyBoardAction:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)handleKeyBoardHide:(NSNotification *)notification {
    CGRect rect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    self.keyBoardHeight = rect.size.height;
    [UIView animateWithDuration:duration animations:^{
        self.keyBoardView.frame = CGRectMake(0, self.view.frame.size.height - self.keyBoardHeight - 44,self.view.frame.size.width, 40);
    }];
}

- (void)handleKeyBoardAction:(NSNotification *)notification {
    double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        self.keyBoardView.frame = CGRectMake(0, self.view.frame.size.height,self.view.frame.size.width, 40);
    }];
}

- (void)itemAction{
    
    
    [self.navigationController pushViewController:[ZYAlreadyAgreedController new] animated:YES];
    
    
    
}

- (void)setNetWork{
    
  //  http://192.168.0.113:8080/StarShine/ws/threeGoodElement.do?action=getElementOrder&id=398
    
    NSString *url = [NSString stringWithFormat:@"threeGoodElement.do?action=getElementOrder&id=%@",self.Id];
    
    
    NSLog(@"%@ %@",LLBaseURLs(url),[AccountTool shareAccountTool].currentAccount.authCode);
    
    
    [NetManager Get:LLBaseURLs(url) Auth:YES Params:nil Success:^(id Obj) {
        [self.dataTowSource removeAllObjects];
        if ([[Obj valueForKey:@"code"] integerValue] == 1000) {
            
            NSDictionary *t = [Obj valueForKey:@"t"];
            
            NSArray *arr = [t valueForKey:@"statistic"];
            NSArray *arrTow = [t valueForKey:@"comments"];
            
            for (NSDictionary *dict in arr) {
                ZYAppointmentModel *model = [ZYAppointmentModel new];
                model.Id = [dict valueForKey:@"id"];
                
                [model setValuesForKeysWithDictionary:dict];
                
                [self.dataSource addObject:model];
            }
            
            for (NSDictionary *dictTow in arrTow) {
                ZYAppointmentTowModel *modelTow = [ZYAppointmentTowModel new];
                modelTow.Id = [dictTow valueForKey:@"id"];
                
                [modelTow setValuesForKeysWithDictionary:dictTow];
                
                [self.dataTowSource addObject:modelTow];
                
            }
            
            
            
            [self.tableView reloadData];
            
            
            
        }
        
    } Fail:^(NSError *Error) {
        
    }];
    
    
   
    
    
    
    
    
}


#pragma mark ----自视图方法的实现
- (void)setUpSuperView{
    
    self.allView = [[UIView alloc]initWithFrame:CGRectMake(0,0,kScreenWidth,44)];
    self.allView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.allView];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(10, self.allView.frame.origin.y + self.allView.frame.size.height, kScreenWidth - 20, kScreenHeight - 64 - 44)];
    self.tableView.backgroundColor = ColorRGB(247, 245, 245);
    self.tableView.delegate = self;
    self.tableView.dataSource =self;
    self.automaticallyAdjustsScrollViewInsets = YES;
    [self.view addSubview:self.tableView];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 200;
    self.tableView.tableFooterView = [UIView new];
    [self.tableView registerClass:[ZYAppointmentCell  class] forCellReuseIdentifier:kCell];
    [self.tableView registerClass:[ZYAppointTowCell  class] forCellReuseIdentifier:kCelll];
     self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //_tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    

    
  
    UIView *mmView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 20)];
    mmView.backgroundColor = ColorRGB(247, 245, 245);
    self.tableView.tableHeaderView =mmView;
    
    UIButton *photoButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    photoButton.frame = CGRectMake(0, 5, kScreenWidth, 30);
    [self.allView addSubview:photoButton];
    [photoButton setImage:[UIImage imageNamed:@"icon_rank_default"] forState:(UIControlStateNormal)];
    [photoButton setTitle:@"   所有要素优秀排序" forState:(UIControlStateNormal)];
    [photoButton setTitleColor:ColorRGB(51, 51, 51) forState:(UIControlStateNormal)];
    photoButton.titleLabel.font = [UIFont systemFontOfSize:15];
    

    

    
    
    
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (0 == section) {
        
        return self.dataSource.count;
    }else{
        
        
        return self.dataTowSource.count;
    }
    
  
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (0 == indexPath.section) {
        ZYAppointmentCell *cell = [tableView dequeueReusableCellWithIdentifier:kCell forIndexPath:indexPath];
        
        if (self.dataSource.count > indexPath.row) {
            
            ZYAppointmentModel *model = self.dataSource[indexPath.row];
            
            [cell assignByZYAppointmentModel:model];
            
            
        }
        
        
        [cell.appintmentButton addTarget:self action:@selector(appintmentButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
        cell.selectionStyle =  UITableViewCellSelectionStyleNone;
        
        return cell;
    }else{
        ZYAppointTowCell *cell = [tableView dequeueReusableCellWithIdentifier:kCelll forIndexPath:indexPath];
        
        if (self.dataTowSource.count > indexPath.row) {
            
            ZYAppointmentTowModel *model = self.dataTowSource[indexPath.row];
            
            [cell assignByZYAppointmentTowModel:model];
            
        }
        cell.delegate = self;
    
        cell.selectionStyle =  UITableViewCellSelectionStyleNone;
        
        return cell;
    }
   
    

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.keyBoardView.textView resignFirstResponder];
}



- (void)appintmentButtonAction:(UIButton *)sender{
    
    ZYAppointmentCell *cell = (ZYAppointmentCell *)sender.superview.superview;
    
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    ZYAppointmentModel *model = self.dataSource[indexPath.row];
    ZYAgreedDetailesController *vc = [ZYAgreedDetailesController new];
    vc.elementId = model.elementId;
    vc.commentId = self.Id;
    vc.name = model.element;
    vc.commentCount = [NSString stringWithFormat:@"%@",[model.elementCount[0] valueForKey:@"commentCount"]];
    
    [self.navigationController pushViewController:vc animated:YES];
    
    
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    if (0 == section) {
        return 20;
    }else{
        return 0;
    }
    
    
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIImageView *view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 20)];
    view.backgroundColor = [UIColor redColor];
    view.image =[UIImage imageNamed:@"add_seg_large_default"];
    return view;
}
















- (void)buttonAction{
    
    
    [self.navigationController pushViewController:[ZYProposalController new] animated:YES];
    
    
}




- (void)tableViewCell:(ZYAppointTowCell *)cell commentses:(UIButton *)commentsBtn{
    
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    ZYAppointmentTowModel *model = self.dataTowSource[indexPath.row];
    
    self.selectId = model.Id;
    
    
    [self.keyBoardView.textView becomeFirstResponder];
    NSLog(@"按钮点击 = %f",CGRectGetMaxY(cell.contentView.frame));
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    CGRect rect = [commentsBtn convertRect:commentsBtn.bounds toView:window];
    [self keyBoardWindowCGRect:rect];
    NSLog(@"%f",CGRectGetMaxY(rect));
    
    
}
//处理键盘
- (void)keyBoardWindowCGRect:(CGRect)rect {
    CGPoint offset = self.tableView.contentOffset;
    offset.y += rect.origin.y + 40 - ([UIScreen mainScreen].bounds.size.height - self.keyBoardHeight - 40);;
    if (offset.y < 0) {
        offset.y = 0;
    }
    [UIView animateWithDuration:0.25 animations:^{
        self.tableView.contentOffset = offset;
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)keyBoardToolShouldEndEditing:(UITextView *)textView {
    NSLog(@"%@",textView.text);
    [self setNetTowWork:textView.text];
}






- (void)setNetTowWork:(NSString *)reply{
    
   
    
    NSString *url = [NSString stringWithFormat:@"threeGoodElement.do?action=saveAdviceReply&id=%@&reply=%@",self.selectId,reply];
    NSString *changeUilStr = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSLog(@"%@  %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
    
    
    [NetManager Get:LLBaseURL(changeUilStr) Auth:YES Params:nil Success:^(id Obj) {
        if ([[Obj valueForKey:@"code"] integerValue] == 1000) {
            [self setNetWork];
        }
        
    } Fail:^(NSError *Error) {
        
    }];
    
 
    
    
}


@end
